// 深拷贝数组/对象
export const deepClone = (value) => {
	if (value == null) return value;  
	if (typeof value !== 'object') return value;
	if (value instanceof RegExp) return new RegExp(value);  
	if (value instanceof Date) return new Date(value);  
	// 判断 value 是对象还是数组 如果是对象 就产生对象 是数组就产生数组  
	let obj = new value.constructor;  
	for(let key in value){    
		obj[key] = deepClone(value[key]); // 看一看当前的值是不是一个对象  
	}  
	return obj;
}

/**
* 参数处理
* @param {*} params  参数
*/
export const tansParams = (params) => {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}

// 封装promise以在async/await下处理错误信息
export const asyncHandle = (promise) => {
  if (!promise || !promise.then) {
      return new Promise((resolve, reject) => {
          reject(new Error("requires promises as the param"));
      }).catch((err) => {
          return [err, null];
      });
  }
  return promise.then(function () {
      return [null, ...arguments];
  }).catch(err => {
      return [err, null];
  });
};
